package com.youkeyi.ddy.cloud.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.youkeyi.ddy.cloud.common.context.YoukeyiSystemContext;
import com.youkeyi.ddy.cloud.common.constant.YoukeyiDdyApplicationSystemConstant;
import com.youkeyi.ddy.cloud.common.context.entity.SystemContextEntity;
import com.youkeyi.ddy.cloud.common.utils.RedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 上下文拦截器
 *
 * @Author liuxiawang
 * @Date 2021-04-08 15:55
 * @Location shenzhen.china
 */
@Component
public class SystemContextInterceptor extends HandlerInterceptorAdapter {
    private Logger logger = LoggerFactory.getLogger(SystemContextInterceptor.class);

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1。从header中获取jwt信息
        // 2。解析jwt的有效数据体，获得各种相关的key
        // 3。将相关的key信息存进ThreadLocal，方便系统获取
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            return super.preHandle(request, response, handler);
        }
        Map<String, String> loginKeyMap;
        try {
            loginKeyMap = new HashMap<>(RedisUtils.getHashMapFromJedis(YoukeyiDdyApplicationSystemConstant.AUTH_REDIS_DB_INDEX, token));
            SystemContextEntity sce = JSON.parseObject(JSON.toJSONString(loginKeyMap), SystemContextEntity.class);
            YoukeyiSystemContext.setUser(sce);
        } catch (Exception e) {
            logger.error("上下文拦截器，获取当前用户数据塞入上下文失败！Token：{}", token);
        }
        return super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //上下文属性值清除，防止内存泄漏
        YoukeyiSystemContext.remove();
        super.afterCompletion(request, response, handler, ex);
    }
}
